package com.bfsuol.bfsuolframework.core.listener;

import com.bfsuol.bfsuolframework.core.BfsuolConstants;
import com.bfsuol.bfsuolframework.core.controller.LoginInfo;
import com.bfsuol.bfsuolframework.core.spring.SpringBeanLoader;
import com.bfsuol.bfsuolframework.security.dao.BaseUser;
import com.bfsuol.bfsuolframework.security.service.BaseUserService;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineInfoListener implements HttpSessionListener {
	private static int activeSessions = 0;

	/* Session创建事件 */
	public void sessionCreated(HttpSessionEvent event) {
		ServletContext ctx = event.getSession().getServletContext();
		Integer numSessions = (Integer) ctx.getAttribute("numSessions");
		if (numSessions == null) {
			numSessions = new Integer(1);
		} else {
			int count = numSessions.intValue();
			numSessions = new Integer(count + 1);
		}
		ctx.setAttribute("numSessions", numSessions);
	}

	/* Session失效事件 */
	public void sessionDestroyed(HttpSessionEvent se) {
		ServletContext ctx = se.getSession().getServletContext();
		Integer numSessions = (Integer) ctx.getAttribute("numSessions");
		if (numSessions == null) {
			numSessions = new Integer(0);
		} else {
			int count = numSessions.intValue();
			numSessions = new Integer(count - 1);
		}
		ctx.setAttribute("numSessions", numSessions);
		// 统计在线时长
		LoginInfo loginInfo = (LoginInfo) se.getSession()
				.getAttribute(BfsuolConstants.SESSION_LOGININFO_KEY);
		if (loginInfo != null) {
			loginInfo.updateLastBrowseTime();
			BaseUserService baseUserService = (BaseUserService) SpringBeanLoader
					.getBean("baseUserServiceImpl");
			BaseUser baseUser = baseUserService.getById(loginInfo.getUserId());
			if (baseUser != null) {
				baseUser.setOnlineTime(baseUser.getOnlineTime() == null ? 0
						: baseUser.getOnlineTime()
								+ loginInfo.getOnlineSeconds());
				baseUserService.updateById(baseUser);
			}
		}

	}
}
